package sample.ws.entity;

import org.springframework.stereotype.Repository;
import sample.ws.util.LocalCacheUtils;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;
import java.util.stream.Collectors;

/**
 * CommonRepository..
 *
 * @author Lizhong
 * @date 2019/7/17
 */
@Repository
public class CommonRepository {

    @PersistenceContext //注入的是实体管理器,执行持久化操作
            EntityManager entityManager;


    public List<Object[]> selectByTableNameAndAttr(Long serviceId, Long page, Long size) {
        String sql = LocalCacheUtils.sqlCache.get(serviceId);

        if (page != null && page > 1 && size != null && size > 0) {
            Long start = (page - 1) * size;
            sql = sql + "limit " + start + "," + size;
        }
        System.out.println(sql);
        List<Object[]> list = entityManager.createNativeQuery(sql).getResultList();
   /*     list.forEach(val -> {
            for (int i = 0; i < val.length; i++) {
                if (val[i] instanceof BigInteger) {
                    val[i] = ((BigInteger) val[i]).longValue();
                }
            }
        });*/
        return list;
    }

    public List<String> queryTableCloumns(String table) {
        Query query = entityManager.createNativeQuery("DESCRIBE " + table);
        List<Object[]> list = query.getResultList();
        List<String> collect = list.stream().map(arr ->
                String.valueOf(arr[0])
        ).collect(Collectors.toList());
        return collect;
    }

}
